If an injected JavaScript code modifies Date class
Date = new Proxy(Date, { ...
or
Date.prototype.toString = function() { ...
on the top level of the window/document, would those override changes apply also to all frames and iframes recursively?
If not, is there a way to force it?
No, and there's no way to do it automatically without modifying the source code of the browser.
You'll have to run your code in every frame explicitly by using one of these methods:
Declare a content script that runs in every frame:
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_start",
"all_frames": true,
"match_about_blank": true
}],
Or add allFrames: true, matchAboutBlank: true to options of chrome.tabs.executeScript.
Or use the nuclear option: chrome.debugger API to attach to the tab and send a CDP command like Page.addScriptToEvaluateOnNewDocument. The downside is that it shows a warning notification on top of every tab.
In cases 1 and 2 the code that overrides the prototypes should be added in page context. Also note that Chrome/Firefox may be unable to run content scripts in certain iframes due to bugs or inherent restrictions, for example iframes with CSP sandbox in Firefox or iframes with src="javascript:..." in Chrome.
Related
I created a Firefox extension that works, for the most part. I am having a hard time importing jQuery. I have downloaded it locally. I am getting no errors. So, sometimes the extension will work and jQuery will load. Sometimes it won't. Other times I have to reload the page 5 or 6 times to get it to work.
I am not a JavaScript developer and this is my first time attempting an extension. I have Googled and tried a bunch of things with no luck.
Below is my manifest.json
"web_accessible_resources" : ["/jquery-3.2.1.min.js","/jquery.csv.min.js","/ui.js"],
"icons": {
"128": "icon_128px.png",
"48": "icon_48px.png"
},
"browser_action": {
"default_icon": "icon_48px.png"
},
"content_scripts": [
{
"matches": ["https://*****.com/*"],
"js": ["content.js"],
"run_at": "document_end"
}
],
"permissions":[
"activeTab"
],
"homepage_url": "https://*****.com"
}
content.js
function injectJs(link) {
var scr = document.createElement("script");
scr.type="text/javascript";
scr.src=link;
(document.head || document.body || document.documentElement).appendChild(scr);
}
injectJs(chrome.extension.getURL("/jquery-3.2.1.min.js"));
injectJs(chrome.extension.getURL("/jquery.csv.min.js"));
injectJs(chrome.extension.getURL("/ui.js"));
Normally, you would load jQuery by including it within the js key in your manifest.json content_scripts entry. For example:
"content_scripts": [
{
"matches": ["https://example.com/*"],
"js": ["jquery-3.2.1.min.js", "jquery.csv.min.js", "ui.js", "content.js"]
}
]
Scripts are loaded in the order listed. So, you need to list the libraries which depend on others after the ones they depend upon (e.g. "jquery-3.2.1.min.js" before "jquery.csv.min.js").
What you were doing
The way that you were doing it inserted the scripts into the page context using <script> tags. Such tags are loaded asynchronously. Thus, there was no guarantee that your scripts which depended on jQuery were actually loaded after jQuery. For what you are doing, you don't want to be loading the scripts into the page context, which is separate from the content script context where your content scripts normally run. If you want more information as to how you can do that successfully, you can see my answer to How to sequentially insert scripts into the page context using tags, which has fully functional code to insert multiple dependent libraries into the page context.
Use .tabs.executeScript() to dynamically load scripts when they are not used 100% of the time
However, if you are loading your content script into a large number of pages (e.g. matches being "<all_urls>", *://*/*, etc.), then you should use a manifest.json content_scripts entry to load only the bare minimum needed to show the initial portion of your user interface (i.e. just the static portion seen prior to the user interacting). Only once the user begins interacting with your user interface should you then send a message, using .runtime.sendMessage(), to your background script, received using .runtime.onMessage(), to instruct your background script to inject the rest of the files needed for your complete user interface. You background script would then use .tabs.executeScript() to load the additional scripts you need and, perhaps, tabs.insertCSS() to inject any additional CSS which you may need.
The point of doing the above is to minimize the impact your extension has on the user/browser during the time which the user is not actively using your extension, which is most of the time under most conditions.
I wrote a firefox addon use webextensions tech. By default firefox load the addon when the page loaded over. But some pages hava slowly loaded js,like some ads or statistics code, so the addon will not load if I stop the unnecessary page load. Or wait a long time before the addon loaded.
So can I setup the addon loaded time? (example: Before the page loaded)
Check out the run_at option in the content_scripts' manifest options. For example, you may use the following options:
content_scripts": [
{
"js": ["my-script.js"],
"matches": ["https://example.org/"],
"match_about_blank": true,
"run_at": "document_start"
}
]
I've got a Google Chrome extension which has the following content script syntax in it's manifest.json:
"content_scripts": [
{
"matches": [
"https://example.com/*"
],
"js": ["js/jquery-2.1.1.js", "js/custom.js"],
"run_at": "document_end",
"all_frames": true
}
],
When testing this extension on an Ember site, it runs on initial page load but after changing the page, it does not get injected again.
For non-Ember users, Ember can update the URL and page content without performing an entire page reload which appears to be causing this issue.
Is anyone aware of a work-around for examples like this?
This was fixed by using chrome.WebNavigation.onHistoryStateChanged which fires every time the page updates.
I am writing a Chrome extension which recognizes certain URL pattern and perform further DOM manipulation. The content script has to get the current URL and matches with the predefined list of URL patterns.
There are two ways I could think of achieving the goal:
The first one would be using location.href
manifest.json
...
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end"
}
],
...
content.js
console.log(location.href);
This method works fine. However, across other similar questions on StackOverflow, they usually suggests using chrome.tabs and message sending from background script to content script as follow:
manifest.json
...
"background" : {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end"
}
],
...
background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.tabs.get(tab.id, function(tabInfo) {
chrome.tabs.sendMessage(tab.id, {
url: tabInfo.url
}, function(response) {
});
})
});
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.url) {
console.log(request.url)
sendResponse(true);
}
return true;
});
Both methods can have the URL correctly. And for the background script, it requires extra memory to keep the background script running in background, compared with content script which is only injected when loading the page.
On the other hand, using background script has benefit as the background script is said to be privileged, it can execute privileged Chrome APIs like the chrome.tabs API.
So as far as I am not using any privileged APIs, should I use the location.href or is there any particular reason most developers suggest using the chrome.tabs and message sending?
Advantages of a background page script:
Complex checks using additional information from the Tab object (N.B. add "tabs" permissions to access url, title, favIconUrl), whereas manifest.json-based injection is limited to URL wildcards/globs.
chrome.declarativeContent API with RequestContentScript action is an example of advanced filtering, it injects the content script(s) based on URL checks and DOM content (only simple selectors as noted in the documentation).
chrome.tabs.executeScript inside chrome.tabs.onUpdated or chrome.webNavigation or chrome.browserAction.onClicked listener to inject the content script(s) only when needed.
Changing the toolbar icon or the browser context menu to reflect change of state; content scripts can't do that, the background page script can.
Accessing privileged API like most of chrome.*, extension's internal storage such as IndexedDB, WebSQL, HTML5 FileSystem, localStorage (the latter is not a good choice though as it's not available in a content script directly, moreover it's synchronous and thus blocks execution).
In all the above cases it makes sense to pass data to content script using messages if that data was used while checking the conditions or it's only available in the background script. Otherwise chrome.storage API inside the content script is as good or could be even better readability-wise.
"Backgroundless" content script is better when all these conditions are met:
URLs to process can be set entirely with wildcards/globs or it really really must be <all_urls>
all required parameters are accessible via chrome.storage API or no parameters needed
no privileged chrome.* APIs are used as those aren't available in content scripts, in other words when the background page is not actually needed.
As for memory consumption: either method may be better or worse depending on how it's used.
If the content script is injected on all pages then each instance will consume memory (some people open 100 tabs so beware!). The worst case case is obviously when both persistent background page and content script on all URLs are used. Non-persistent event page might help but in a limited fashion because chrome.tabs.onUpdated is likely to run pretty frequently forcing the event page to reload (which also takes some time).
I'm developing a chrome extension that requires a content_script to add custom controls to a media player. However, I want to allow users to set the domain of the player via an options control panel (for their personal media servers).
It seems like the domain for content scripts has to be set statically in the manifest.json file in the chrome extension. Is there a way to set that programmatically? To achieve something like this:
"content_scripts": [
{
"matches": ["<variable_from_config>"],
"js": ["player.js"],
"run_at": "document_start"
}
]
You can use the new contentScripts.register() API, which does exactly what you want: programmatically registers content scripts.
browser.contentScripts.register({
matches: ['https://your-dynamic-domain.example.com/*'],
js: [{file: 'content.js'}]
});
This API is only available in Firefox but there's a Chrome polyfill you can use.
For that to work, you'll still need permission to the domain you want to register the script on, so you can use optional_permissions in the manifest and chrome.permissions.request to let the user add new domains on demand.
I also wrote some tools to further simplify this for you and for the end user, such as
webext-domain-permission-toggle and webext-dynamic-content-scripts. They will also register your scripts in the next browser launches and allow the user the remove the new permissions and scripts.