"window is not defined" with nuxtjs. Trying to build pages with generate - window

I get the error message "window is not defined" if I use "window" in my default.vue template inside layouts folder. Building static pages with "npm run generate" creates the error message. Mode is set to "universal"
...
created() {
window.addEventlistener('scroll', e => {
console.log('scrollleeed')
})
}
...
What I'm doing wrong? I thought "generate" will create static pages and everything will be executed on the client side.
Solution
I have to use the mounted hook, not created for window or document related stuff

generate will render pages on server, but only once e.g. at build time. But still to create static pages you need to render them on server, and hence that error
To avoid it you need to use window inside mounted, or wrap it with if (process.client) {}

Related

Cypress: Prevent open new tab with link dynamically created and clicked

I want to test a file download. It is made programmatically on click a button that uses this function:
export function downloadURI(uri, target) {
const link = document.createElement('a')
if (target) link.target = target
link.href = uri
link.click()
}
The problem is that when you do cy.click() on that button the new tab is opened and the tests fail. I am checking that the download is successful by asserting the loading modal is visible after clicking the button (while the file is being generated via an HTTP request) and is Not visible after the download was generated.
How can I prevent this tab from opening so that the tests do not fail?
This works for me:
cy.get('a').invoke('removeAttr', 'target').click()
From the official document it says that cypress does not support multiple tabs testing.
Also there is a recipe including 3 solutions about how to handle this.
Have a read and see if it can help.

How to run AppleScript from inside a SwiftUI View?

I'm kind of getting some more understanding with basic SwiftUI but now I wanted to extend my application to actually do some stuff regarding system components for me. Basically I want to run an AppleScript from inside my app which creates a signature in Mac Mail. The script itself is pretty simple:
// Generates a signature in Mac Mail
tell application "Mail"
set newSig to make new signature with properties {name:"The Signature Name"}
set content of newSig to "My New Signature Content"
end tell
I have created a view with a button which should execute the script:
import SwiftUI
struct SomeView: View {
#State var status = ""
var body: some View {
VStack(alignment: .center) {
Button(action: {
let source = """
tell application \"Mail\"
set newSig to make new signature with properties {name: \"The Signature Name\"}
set content of newSig to \"My New Signature Content\"
end tell
"""
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: source) {
if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(&error) {
self.status = output.stringValue ?? "some default"
} else if (error != nil) {
self.status = "error: \(error)"
}
}
}) {
Text("Generate").font(.callout)
}
Text("\(self.status)")
}
}
}
struct SomeView_Previews: PreviewProvider {
static var previews: some View {
SomeView()
}
}
Everything executes but I get the error
AppleScript run error = {
NSAppleScriptErrorAppName = Mail;
NSAppleScriptErrorBriefMessage = "Application isn\U2019t running.";
NSAppleScriptErrorMessage = "Mail got an error: Application isn\U2019t running.";
NSAppleScriptErrorNumber = "-600";
NSAppleScriptErrorRange = "NSRange: {0, 0}";
}
After some research i found this article which describes the problem quite well. Apparently this error is because the app is running in a sandbox and within the sandbox Mail is indeed not running. I kind of get Apple's idea not to let applications do whatever they want without the user's consent...
Anyway, unfortunately this article describes the solution using Objective C and this is something I have even less of a clue than SwiftUI.
Can anybody tell me how to run (or copy my script.scpt file to the accessible library folder and the run) a script from within a SwitUI View? This would be so much help!
Thanks!!!
I have played around quite a bit with this manner and after having numerous discussions and trial & errors on that subject, I want to present 2 solutions (until now it seems that these are the only possible solutions for a sandboxed application).
First of all, if you don't consider to distribute your app on the App Store, you can forget about the following, since you just have to deactivate the Sandbox and you are basically free to do whatever you want!
In case your planning to distribute a Sandboxed App, the only way of running a script and interacting with other apps on the user's system is to run a script file from the Application Script folder. This folder is a designated folder in the user library structure: /Users/thisUser/Library/Application Scripts/com.developerName.appName/. Whatever script goes in here you have the right to run from your application appName.
You basically have two options to get your script file into that folder:
Option 1 - Install the Script File
This is (in my opinion) clearly the option you should go for if your script is static (does not require any additional user data from your application). All you have to do is
Select the project (1)
click on Build Phases (2)
add the Copy Files setting (if not already present)
choose the script file location in your app (singing might be a good option when distributing via AppStore)
add the Application Script folder of your application to the destination. Therefore, choose Absolute Path and enter Users/$USER/Library/Application Scripts/$PRODUCT_BUNDLE_IDENTIFIER in the Path field.
You can also select the Copy only when installing option if your script is entirely static but in case you have changes on the script when the application is closed and reopened and you want to update the script, leave this option blank (I have not tested this!).
After this is done you can execute the script via NSUserScriptTask. A more detailed description of how you could implement this is given here.
Option 2 - Giving access to the folder and copy the file on demand
This is certainly the solution when your script file updates dynamically according to e.g. user inputs. Unfortunately, this is a bit of a hassle and does not have (in my opinion) satisfying solutions. To do so, you will have to grant access to the folder (in this case Application Scripts/). This is done via NSOpenPanel. A really good tutorial how to implement this is given here.
Per default you will have read permission to that folder only. Since you are trying to copy a file into that folder you will have to change that to read/write in your Capabilities as well.
I hope this will help some people to "shine some light into the dark"! For me this was quite a bit of a journey since there is only very little information out there.

Vuepress oidc-client preventing build

It looks like Vuepress is made for public docs, but we decided to add client and server security to protect some of the doc pages. But unfortunately although oidc-client (https://github.com/IdentityModel/oidc-client-js/wiki) works during dev, it throws exception when build.
I get ReferenceError: window is not defined and when I try to trick the compiler with const window = window || { location: {} }; I get TypeError: Cannot read property 'getItem' of undefined
Any idea how to make this work?
This was driving me nuts also. I discovered the component I was trying to add was looking at window.location in its code - this was triggering the error.
My understanding is that the build process has not access to Browser things like window etc.
As soon as I removed the window.location bit from my code things built just fine and all is well.

An app can’t load remote web content in the local context

working on cordova [ windows 8.1 app ] maps api is not loading with error [Error] An app can’t load remote web content in the local context.
causes of issue :
1) google maps loads asyncly
2) windows app doesn't allow dynamic script insertion
3) win app runs in local context and doesn't allow to load anything from web(remote context) see this comment [ http://msopentech.com/blog/2014/09/25/apache-cordova-gains-windows-8-1-and-windows-phone-8-1-support-2-2/#comment-12911 ]
4) getting same error even in an iframe .
define('gmaps',['async!http://maps.google.com/maps/api/js?v=3.17&sensor=false&libraries=geometry'],
function(){
// return the gmaps namespace for brevity
return window.google.maps;
});
progress solved :
2) https://github.com/msopentech/winstore-jscompat
4) able to load google map in i frame . now how can i pass google object to parent window ?
Update :
didn't find any solution for this issue
we switched to native app.
When you call a google maps api asynchronously You need put a callback in the end of the url, check this little example:
https://developers.google.com/maps/documentation/javascript/examples/map-simple-async?hl=es
Now, you can play with google maps api with a callback trick defining before call asynchronously:
window["mycallback"] = function(){
return "hello I'm called when all API is loaded :D"
}
And then calling with that url
http://maps.google.com/maps/api/js?v=3.17&sensor=false&libraries=geometry&callback=mycallback
Try with that, I hope to help with that

Debugging Content Scripts for Chrome Extension

General Questions
Hello! I'm delving into the world of Chrome Extensions and am having some problems getting the overall workflow down. It seems that Google has recently switched to heavily advocating Event Pages instead of keeping everything in background.js and background.html. I take part of this to mean that we should pass off most of your extension logic to a content script.
In Google's Event Page primer, they have the content script listed in the manifest.json file. But in their event page example extension, it is brought in via this code block in background.js: chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() { });
What are the advantages of doing it one way over the other?
My Code
I'm going forward with the programatic way of injecting the content script, like Google's example.
manifest.json
{
"manifest_version": 2,
"name": "Test",
"description": "Let's get this sucker working",
"version": "0.0.0.1",
"permissions": [
"tabs",
"*://*/*"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png"
}
}
background.js
chrome.browserAction.onClicked.addListener(function() {
console.log("alert from background.js");
chrome.tabs.executeScript({file: "jquery-2.0.2.min.js"}, function() {
console.log("jquery Loaded");
});
chrome.tabs.executeScript({file: "content.js"}, function() {
console.log("content loaded");
});
});
content.js
console.log('you\'r in the world of content.js');
var ans = {};
ans.createSidebar = function() {
return {
init: function(){
alert("why hello there");
}
}
}();
ans.createSidebar.init();
I am able to get the first 3 console.log statements to show up in the background page's debugger. I'm also able to get the alert from content.js to show up in any website. But I'm not able to see the console.log from content.js, nor am I able to view any of the JS from content.js. I've tried looking in the "content scripts" section of the background page debugger's Sources tab. A few other posts on SO have suggested adding debugger; statements to get it to show, but I'm not having any luck with anything. The closest solution I've seen is this post, but is done by listing the content script in the manifest.
Any help would be appreciated. Thanks!
Content scripts' console.log messages are shown in the web page's console instead of the background page's inspector.
Adding debugger; works if the Developer Tool (for the web page where your content script is injected) is opened.
Therefore, in this case, you should first activate the Developer Tool (of the web page) before clicking the browser action icon and everything should work just fine.
I tried to use the debuggermethod, but it doesn't not work well because the project is using require.js to bundle javascript files.
If you are also using require.js for chrome extension development, you can try adding something like this to the code base, AND change eval(xhr.responseText) to eval(xhr.responseText + "\n//# sourceURL=" + url);. (like this question)
Then you can see the source file in your dev tool (but not the background html window)
manifest v3
You can add console.log statements to your content scripts.
This is one of the best ways to debug an application.
Let's say you want to access a DOM node from the content script.
const node = document.querySelector("selector")
node will be Element instance if it exists else it will be null
If you can see the node in the Elements tab but not able to access it via content script then the node might have not been loaded at the time you accessed it.
Follow this answer to fix this issue.

Resources