UniversityExam

Как выполнить скрипт, в той вкладке браузера в которой мы находимся, из popup меню , расширения

Как выполнить скрипт, в той вкладке браузера в которой мы находимся, из popup меню , расширения? Когда я нажимаю на расширение, открывается попап меню, там есть кнопка, которая вызывает скрипт. Но, этот скрипт должен выполняться на той странице в которой мы находимся, а не в popup.html . Как так сделать? Если я этот скрипт через консоль вставляю, все отрабатывает. То есть как получить доступ к странице что бы там можно было выполнить скрипт в её окружении? У меня там ratiobutton (на веб-старницы к которой будет применяться плагин) и хочу их просто включать через скрипт. вот мой манифест

 < "name": "test", "version": "2", "manifest_version": 2, "description": "Test!", "icons": < "16" : "images/GB-19.png", "48" : "images/GB-48.png", "128" : "images/GB-128.png" >, "browser_action": < "default_icon": "images/GB-19.png", "default_title": "TestExam", "default_popup": "popup.html" >, "permissions": ["tabs","activeTab"] > 
        

a b c d e f g h

popup не доступна текущая страница ни в каком виде. Вам надо сделать content script, который будет загружен на этой странице и общаться с этим скриптом через сообщения (см. chrome.runtine.onMessage, chrome.runtime.sendMessage, chrome.tabs.sendMessage) Из контент скрипта вы получите доступ к текущему document таба на котором он загрузился, но при этом не получите доступ к JS коду самой страницы, но вот это последнее ограничение в принципе обойти можно, только обычно не нужно

Источник

Running Javascript in new window.open

This successfully creates a new window with the HTML in it. I have a bunch of HTML tags which when clicked run a function called Foo1. I’ve tried printing the entire function of Foo1 to the new HTML document, and tried putting Foo1 inside myScript.js. I see both Foo1 inside a script tag in the new window, and but neither are loaded since they are just written to the new page as HTML.

Читайте также:  Java sum array integers

Scripts don’t run when you assign them to .innerHTML . You need to call createElement(‘script’) and add it to the window’s DOM.

You are putting a complete HTML document inside the body of another HTML document. What do you expect to happen?

4 Answers 4

Scripts added with .innerHTML aren’t executed. You need to create a script node and append it to the window’s DOM.

$("#button").click(newWindow); function newWindow(id) < var html = $(id).html(); var win = window.open(''); win.document.head.innerHTML = ''; win.document.body.innerHTML = '' + html + ''; var script = document.createElement('script'); script.src = 'js/myScript.js'; win.document.head.appendChild(script); >

This doesn’t run in Stack Snippet’s sandbox, here’s a working jsfiddle.

Thanks this worked, I was looking the the wrong places for the solution. I wasn’t aware I could append new node types to a new window in this manner. Thanks again!

var newWindow = window.open(''); newWindow.document.createElement('script'); script.src = 'js/myScript.js'; newWindow.document.head.appendChild(script); 

Just in case someone has this to be done in a link. Do the following:

This opens a new window with that URL, it set the focus to that windows, and as soon as the ‘load’ event is triggered, it executes the code in the function. It only works with a page in the same domain.

Here’s how you create, and then append a script file within a new window:

var fileref = document.createElement('script'); //creates script in current document fileref.setAttribute("type", "text/javascript") //set it to JS by "type" fileref.setAttribute("src", filename) //set your "src=yourFile_href_Here.js" //Then create your newWindow as you did above, but slightly updated //Create your function which will consume the "fileref" argument function htmlNewWindow(fileref) < var newWindow = window.open(''); newWindow.document.getElementsByTagName("head")[0].appendChild(fileref); >; //right now the function is made but you still have to execute it //Execute your function, and pass it the variable "fileref" that you set above. htmlNewWindow(fileref); //Within this edit you will append the head element //with your newly created script(or any other parameterized argument) /* Replace your filename to pass any other script */ 

Источник

Inject an opened window with script

This question asks for a way to open a new window using window.open and then inject it with a script. It was not possible because of cross-domain security issues. However, my problem is that I want to do the exact same thing, except from the same domain to the same domain. Is this possible? Note that .write does not solve this problem because it wipes all the html from the page first.

3 Answers 3

You can do something like this:

var theWindow = window.open('http://stackoverflow.com'), theDoc = theWindow.document, theScript = document.createElement('script'); function injectThis() < // The code you want to inject goes here alert(document.body.innerHTML); >theScript.innerHTML = 'window.onload = ' + injectThis.toString() + ';'; theDoc.body.appendChild(theScript); 

This also seems to work:

var theWindow = window.open('http://stackoverflow.com'), theScript = document.createElement('script'); function injectThis() < // The code you want to inject goes here alert(document.body.innerHTML); >// Self executing function theScript.innerHTML = '(' + injectThis.toString() + '());'; theWindow.onload = function () < // Append the script to the new window's body. // Only seems to work with `this` this.document.body.appendChild(theScript); >; 

And if for some reason you want to use eval:

var theWindow = window.open('http://stackoverflow.com'), theScript; function injectThis() < // The code you want to inject goes here alert(document.body.innerHTML); >// Self executing function theScript = '(' + injectThis.toString() + '());'; theWindow.onload = function () < this.eval(theScript); >; 

What this does (Explanation for the first bit of code. All examples are quite similar):

  • Opens the new window
  • Gets a reference to the new window’s document
  • Creates a script element
  • Places all the code you want to ‘inject’ into a function
  • Changes the script’s innerHTML to load said function when the window loads, with the window.onload event (you can also use addEventListener ). I used toString() for convenience, so you don’t have to concatenate a bunch of strings. toString basically returns the whole injectThis function as a string.
  • Appends the script to the new window’s document.body , it won’t actually append it to the document that is loaded, it appends it before it loads (to an empty body), and that’s why you have to use window.onload , so that your script can manipulate the new document.

It’s probably a good idea to use window.addEventListener(‘load’, injectThis.toString()); instead of window.onload , in case you already have a script within your new page that uses the window.onload event (it’d overwrite the injection script).

Note that you can do anything inside of the injectThis function: append DIVs, do DOM queries, add even more scripts, etc.

Also note that you can manipulate the new window’s DOM inside of the theWindow.onload event, using this .

Источник

Оцените статью